import numpy
import scipy
import pylab
import re
import glob

from utils import LoadFile
from dparams import FindParams,pdistFunc,GAFindParams
from Envelope import Envelope

if __name__=='__main__':
    sParams=[]
    xParams=[]
    yParams=[]
    while True:
        if not globals().has_key("Index"):
            Index=0
            files=glob.glob('data/*_direct*.log')
            print "file:",files[0]
            data=LoadFile(files[0])
            sizes=data[:,1]
            WCTimes=data[:,3]
            IOTimes=data[:,5]
            rusage=data[:,6]
            rates=data[:,8]
            MRUTimes=data[:,7]
            ix=numpy.argsort(sizes)
            Sizes    = numpy.array(sizes)[ix]
            WCTimes  = numpy.array(WCTimes)[ix]
            CPUTimes = numpy.array(rusage)[ix]
            IOwait   = numpy.array(IOTimes)[ix]
            Rates    = numpy.array(rates)[ix]
            MRUTimes   = numpy.array(MRUTimes)[ix]
            difsizes=sorted(list(set(Sizes)))
        else: Index+=1
            
        fig=pylab.figure(num=6,figsize=(15,8))
        pylab.ion()
        pylab.clf()
        i=Index
        #for i in range(len(difsizes)):
        jj=numpy.where(Sizes==difsizes[i])
        x=Sizes[jj]
        y=WCTimes[jj]
        y1=IOTimes[jj]
        Y,XL=numpy.histogram(y,bins=100)
        X=0.5*(XL[1:]+XL[:-1])
        eX,eY=Envelope(X,Y,low=False)
        params=GAFindParams(eX,eY)
        sParams.append(difsizes[i])
        xParams.append(params[1]+2.0/params[2])
        yParams.append(numpy.sqrt(2.0/params[2]**2))
        pylab.subplot(211)
        pylab.hist(y,bins=100,alpha=0.3,label="Wall")
        pylab.hist(y1,bins=100,alpha=0.3,label="IOw")
        feY=pdistFunc(params,eX)
        pylab.plot(eX,eY,'.-',label="IO") 
        pylab.plot(eX,feY,'.-',label="pdist IO")
        #pylab.xlim((min(WCTimes),max(y)))
        pylab.title("Size:%4.3f [MB]"%difsizes[i])
        pylab.legend()
        pylab.subplot(212)
        pylab.grid(b=True,which='both')
        pylab.plot(sParams,xParams,'.-',label="thresh io time")
        pylab.plot(sParams,yParams,'.-',label="spread io time")
        pylab.legend()
        pylab.draw()
        key=pylab.waitforbuttonpress(10)
        if key!=None:
            continue
        elif key==True:
            break
        
        
